package com.aluka.nirvana.framework.security.principal;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户对象基类
 * @author gongli
 * @since 2019/4/10 13:40
 */
@Data
public class BaseUserDetails implements UserDetails {

    public static final String CLIENT_ROLE = "CLIENT";

    private String userId;

    private String username;

    private String password;

    private boolean accountNonExpired;

    private boolean accountNonLocked;

    private boolean enabled;

    private boolean admin;

    private Collection<? extends GrantedAuthority> authorities;

    private Map<String, Object> customFields;

    public Object getCustomField(String name){
        if(customFields == null){
            return null;
        }
        return customFields.get(name);
    }

    public void putCustomField(String name, Object value){
        if(customFields == null){
            customFields = new HashMap<>();
        }
        customFields.put(name, value);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return  this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    public boolean isClient() {
        for (GrantedAuthority authority : authorities) {
            if(CLIENT_ROLE.equals(authority.toString())){
                return true;
            }
        }
        return false;
    }

    public static BaseUserDetails buildClientUser(){
        BaseUserDetails userDetails = new BaseUserDetails();
        userDetails.setUsername("client");
        userDetails.setPassword("client");
        userDetails.setUserId("client");
        userDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(CLIENT_ROLE));
        return userDetails;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

}
